package com.lishangshan.oas_system.controller.mail;

import com.github.pagehelper.util.StringUtil;
import com.lishangshan.oas_system.common.formValid.BindingResultVOUtil;
import com.lishangshan.oas_system.common.formValid.MapToList;
import com.lishangshan.oas_system.common.formValid.ResultEnum;
import com.lishangshan.oas_system.common.formValid.ResultVO;
import com.lishangshan.oas_system.model.dao.maildao.InMailDao;
import com.lishangshan.oas_system.model.dao.maildao.MailnumberDao;
import com.lishangshan.oas_system.model.dao.maildao.MailreciverDao;
import com.lishangshan.oas_system.model.dao.notedao.AttachmentDao;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.mail.Inmaillist;
import com.lishangshan.oas_system.model.entity.mail.Mailnumber;
import com.lishangshan.oas_system.model.entity.mail.Mailreciver;
import com.lishangshan.oas_system.model.entity.mail.Pagemail;
import com.lishangshan.oas_system.model.entity.note.Attachment;
import com.lishangshan.oas_system.model.entity.user.User;
import com.lishangshan.oas_system.service.mail.MailServices;
import com.lishangshan.oas_system.service.process.ProcessService;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/")
public class MailController {
    @Autowired
    private MailreciverDao mailreciverDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private InMailDao inMailDao;
    @Autowired
    private MailServices mailServices;
    @Autowired
    private StatusDao statusDao;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private MailnumberDao mailnumberDao;
    @Autowired
    private MailControllerFun mailControllerFun;

    /**
     * 邮件管理初始化
     *
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("mail")
    public String mail(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model, @SessionAttribute("userId") Long userId) {
        //配置 分页属性
        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MIN);
        User user = userDao.findOne(userId);// 根据 userId查询当前用户
        List<Mailreciver> noMails = mailreciverDao.findByReadAndDelAndReciverId(false, false, user); // 未读邮件 ，第一个false 代表未读，第二个false 代表未删除
        model.addAttribute("noread", noMails.size()); // 向前台传值，多少条未读邮件数据

        List<Inmaillist> setmail = inMailDao.findByPushAndDelAndMailUserid(true, false, user); // false 代表未删除 ，user 代表当前用户
        model.addAttribute("push", setmail.size()); // 向前台传值，多少条已发邮件数据

        List<Inmaillist> nopushMail = inMailDao.findByPushAndDelAndMailUserid(false, false, user); // 查找 草稿
        model.addAttribute("nopush", nopushMail.size()); // 存储草稿邮箱数量

        List<Mailreciver> rubbishMail = mailreciverDao.findByDelAndReciverId(true, user);// true 代表已删除，逻辑删除
        model.addAttribute("rubbish", rubbishMail.size()); //  向前台传值，多少条已删除邮件数据

        /* 以上是侧边数据 回传，下面做表格展示页面  */
        model.addAttribute("mess", "收件箱");
        model.addAttribute("sort", "&title=收件箱");
        Page<Pagemail> pageMails = mailreciverDao.findmail(user, false, pa);// 初始化表格数据时，直接展示收件箱分页查询
        List<Map<String, Object>> mailList = mailServices.mail(pageMails); // 封裝前台展示数据
        model.addAttribute("page", pageMails);// 存储分页数据
        model.addAttribute("maillist", mailList);// 存储表格当前展示数据
        model.addAttribute("url", "mailtitle");
        return "mail/mail";
    }

    /**
     * 根据标题不同来查找不同的数据
     *
     * @param title
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping("amail")
    public String amail(@RequestParam("title") String title, @SessionAttribute("userId") Long userId,
                        @RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model
    ) {
        String val = null;
        int size = ParameterUtil.PAGE_SIZE_MIN;
        System.out.println("title=" + title);
        User user = userDao.findOne(userId);
        mailControllerFun.paginfo(title, page, size, user, model, val);
//        Pageable pa = new PageRequest(page, ParameterUtil.PAGE_SIZE_MAX);
     /*   Page<Pagemail> pagelist = null;
        Page<Inmaillist> pagemail = null;
        List<Map<String, Object>> maillist = null;
        if (("收件箱").equals(title)) {
            //分页及查找
            pagelist = mailServices.recive(page, size, user, null, title);
            maillist = mailServices.mail(pagelist);
        } else if (("发件箱").equals(title)) {
            pagemail = mailServices.inmail(page, size, user, null, title);
            maillist = mailServices.maillist(pagemail);
        } else if (("草稿箱").equals(title)) {
            pagemail = mailServices.inmail(page, size, user, null, title);
            maillist = mailServices.maillist(pagemail);
        } else {
            //垃圾箱
            //分页及查找
            pagelist = mailServices.recive(page, size, user, null, title);
            maillist = mailServices.mail(pagelist);

        }

        if (!Objects.isNull(pagelist)) {
            model.addAttribute("page", pagelist);
        } else {
            model.addAttribute("page", pagemail);

        }
        System.out.println("maillist = " + maillist);
        model.addAttribute("maillist", maillist);
        model.addAttribute("url", "mailtitle");
        model.addAttribute("mess", title);
        model.addAttribute("sort", "&title=" + title);*/
        return "mail/allmail";
    }

/*    private Map<String, Object> paginBranch(String title, int page, int size, User user, Model model, String val) {
        Page<Pagemail> pagelist = null;
        Page<Inmaillist> pagemail = null;
        List<Map<String, Object>> maillist = null;
        HashMap<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(val)) {

        } else {

        }
        map.put("pagelist", pagelist);
        map.put("pagemail", pagemail);
        map.put("maillist", maillist);
        return map;
    }*/
    //    mailtitle

    /*前端异步加载邮件数量*/
    @RequestMapping("/getNumber")
    @ResponseBody
    public Map<String, Object> getNumber(@SessionAttribute("userId") Long userId) {
        // 查找用户
        User user = userDao.findOne(userId);
        // 查找未读邮件
        List<Mailreciver> noreadlist = mailreciverDao.findByReadAndDelAndReciverId(false, false, user);
        // 查找创建了但是却没有发送的邮件
        List<Inmaillist> nopushlist = inMailDao.findByPushAndDelAndMailUserid(false, false, user);
        // 查找发件条数
        List<Inmaillist> pushlist = inMailDao.findByPushAndDelAndMailUserid(true, false, user);
        // 查找收件箱删除的邮件条数
        List<Mailreciver> rubbish = mailreciverDao.findByDelAndReciverId(true, user);
        Map<String, Object> map = new HashMap<>();
        map.put("noread", noreadlist.size());
        map.put("nopush", nopushlist.size());
        map.put("push", pushlist.size());
        map.put("rubbish", rubbish.size());
        return map;
    }

    /**
     * 分页 搜索 类型 查找
     *
     * @param page
     * @param size
     * @param req
     * @param title
     * @param userId
     * @return
     */
    @RequestMapping("mailtitle")
    public String mailPaging(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model,
                             @RequestParam(value = "size", defaultValue = "5") int size, HttpServletRequest req,
                             @RequestParam(value = "title", required = false) String title, @RequestParam(value = "val", required = false) String val,
                             @SessionAttribute("userId") Long userId) {
//        String val1 = req.getParameter("val");
        if (val == null) {
            val = "";
        }
        System.out.println("val = " + val);
        System.out.println("title =" + title);
        User user = userDao.findOne(userId);
        Pageable pa = new PageRequest(page, size);
        Page<Pagemail> pagelist = null;
        Page<Inmaillist> pagemail = null;
        List<Map<String, Object>> maillist = null;
        // 如果 val为空则是搜索框进行查找
       /* if (!StringUtils.isEmpty(val)) {
            if (("收件箱").equals(title)) {
                //分页及查找
                pagelist = mailServices.recive(page, size, user, null, title);
                maillist = mailServices.mail(pagelist);
            } else if (("发件箱").equals(title)) {
                pagemail = inMailDao.findbymailUseridAndPushAndDel(user, false, false, val, pa);
                maillist = mailServices.maillist(pagemail);
            } else if (("草稿箱").equals(title)) {
                pagemail = inMailDao.findbymailUseridAndPushAndDel(user, false, false, val, pa);
                maillist = mailServices.maillist(pagemail);
            } else {
                //垃圾箱
                //分页及查找
                pagelist = mailreciverDao.findmails(user, false, val, pa);
                maillist = mailServices.mail(pagelist);
            }
            if (!Objects.isNull(pagelist)) {
                model.addAttribute("page", pagelist);
            } else {
                model.addAttribute("page", pagemail);

            }
            model.addAttribute("maillist", maillist);
            model.addAttribute("url", "mailtitle");
            model.addAttribute("mess", title);
            model.addAttribute("sort", "&title=" + title);
        } else {
            if (!StringUtils.isEmpty(title)) {
                paginfo(title, page, size, user, model, val);
            }
        }*/
        mailControllerFun.paginfo(title, page, size, user, model, val.trim());
        return "mail/mailbody";
    }

    @Autowired
    private ProcessService processService;

    /**
     * 写信，编辑，回复 转发跳转
     *
     * @param model
     * @param userId
     * @param request
     * @param page
     * @return
     */
    @RequestMapping("wmail")
    public String redact(Model model, @SessionAttribute("userId") Long userId, HttpServletRequest request,
                         @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "id", required = false) Long id) {
        int size = ParameterUtil.PAGE_SIZE_MIN;
        User mu = userDao.findOne(userId);
        //得到编辑过来的id
 /*       if (!StringUtils.isEmpty(request.getParameter("id"))) {
            id = Long.parseLong(request.getParameter("id"));
        }*/
        //回复那边过来的
        String huifu = request.getParameter("huifu");
        Inmaillist mail = null;
        mailControllerFun.redactInfo(id, mail, huifu, model);// 根据id和huifu来判断是该存储啥
        //查看该用户所创建的有效邮箱账号
        List<Mailnumber> mailnum = mailnumberDao.findByStatusAndMailUserId(1L, mu);
        processService.user(page, size, model);
        model.addAttribute("mailnum", mailnum);
        return "mail/wirtemail";
    }

    /**
     * 查看邮件
     */
    @RequestMapping("smail")
    public String index4(HttpServletRequest req, @SessionAttribute("userId") Long userId, Model model) {
        User mu = userDao.findOne(userId);
        //邮件id
        Long id = Long.parseLong(req.getParameter("id"));
        //title
        String title = req.getParameter("title");
        //找到中间表信息
        if (("收件箱").equals(title) || ("垃圾箱").equals(title)) {
            Mailreciver mailr = mailreciverDao.findbyReciverIdAndmailId(mu, id);
            mailr.setRead(true);
            mailreciverDao.save(mailr);
        }

        //找到该邮件信息
        Inmaillist mail = inMailDao.findOne(id);
        String filetype = null;
        if (!Objects.isNull(mail.getMailFileid())) {
            String filepath = mail.getMailFileid().getAttachmentPath();
            System.out.println(filepath);
            if (mail.getMailFileid().getAttachmentType().startsWith("image")) {
                filetype = "img";
            } else {
                filetype = "appli";

            }
            model.addAttribute("filepath", filepath);
            model.addAttribute("filetype", filetype);
        }

        User pushuser = userDao.findOne(mail.getMailUserid().getUserId());
        model.addAttribute("pushname", pushuser.getUserName());
        model.addAttribute("mail", mail);
        model.addAttribute("mess", title);
        model.addAttribute("file", mail.getMailFileid());

        return "mail/seemail";
    }

    @Autowired
    private AttachmentDao attachmentDao;

    /**
     * 存草稿/发送
     *
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping("pushmail")
    public String push(@RequestParam("file") MultipartFile file, HttpServletRequest request, @Valid Inmaillist mail, BindingResult br, @SessionAttribute("userId") Long userId) throws IllegalStateException, IOException {
        User tu = userDao.findOne(userId);
        String name = null;
        Attachment attaid = null;
        Mailnumber number = null;
        StringTokenizer st = null;
        ResultVO res = BindingResultVOUtil.hasErrors(br);
        if (!ResultEnum.SUCCESS.getCode().equals(res.getCode())) {
            List<Object> list = new MapToList<>().mapToList(res.getData());
            request.setAttribute("errormess", list.get(0).toString());
        } else {
            if (!StringUtil.isEmpty(request.getParameter("fasong"))) {
                name = request.getParameter("fasong");
            }


            if (!StringUtil.isEmpty(name)) {
                if (!StringUtil.isEmpty(file.getOriginalFilename())) {
                    attaid = mailServices.upload(file, tu);
                    attaid.setModel("mail");
                    attachmentDao.save(attaid);
                }
                //发送成功
                mail.setPush(true);

            } else {
                //存草稿
                mail.setInReceiver(null);
            }
            mail.setMailFileid(attaid);
            mail.setMailCreateTime(new Date());
            mail.setMailUserid(tu);
            if (!mail.getInmail().equals(0)) {
                number = mailnumberDao.findOne(mail.getInmail());
                mail.setMailNumberid(number);
            }
            //存邮件
            Inmaillist imail = inMailDao.save(mail);

            if (!StringUtil.isEmpty(name)) {
                if (mailServices.isContainChinese(mail.getInReceiver())) {
                    // 分割任务接收人
                    StringTokenizer st2 = new StringTokenizer(mail.getInReceiver(), ";");
                    while (st2.hasMoreElements()) {
                        User reciver = userDao.findid(st2.nextToken());
                        Mailreciver mreciver = new Mailreciver();
                        mreciver.setMailId(imail);
                        mreciver.setReciverId(reciver);
                        mailreciverDao.save(mreciver);
                    }
                } else {
                    if (mail.getInReceiver().contains(";")) {
                        st = new StringTokenizer(mail.getInReceiver(), ";");
                    } else {
                        st = new StringTokenizer(mail.getInReceiver(), "；");
                    }

                    while (st.hasMoreElements()) {
                        if (!StringUtil.isEmpty(file.getOriginalFilename())) {
                            mailServices.pushmail(number.getMailAccount(), number.getPassword(), st.nextToken(), number.getMailUserName(), mail.getMailTitle(),
                                    mail.getContent(), attaid.getAttachmentPath(), attaid.getAttachmentName());

                        } else {
                            mailServices.pushmail(number.getMailAccount(), number.getPassword(), st.nextToken(), number.getMailUserName(), mail.getMailTitle(),
                                    mail.getContent(), null, null);
                        }
                    }
                }

            }
        }
        return "redirect:/mail";
    }
}
